import { message, serverLoading } from '@library/utils';

type DataProps = {
  businessId?: string;
  [prop: string]: any;
};

export const Admin = 'ADMIN';
export const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}');
export function handleUserId() {
  return userInfo?.userType === Admin ? Admin : userInfo.id;
}

export const cacheKeyFun = (businessId: string) => handleUserId() + '__' + businessId;

export const columnsMapObj: Record<string, any> = {};

export const setColumnsApi = async (data: DataProps) => {
  try {
    const id = data.id;
    const result = await serverLoading(`/bk/api/company/UserCustomization/${id ? 'update' : 'add'}`, {
      data: { ...data, id, userId: handleUserId() }
    });

    data.id = result.id;
    columnsMapObj[cacheKeyFun(data.businessId!)] = result;

    message.success();

    return result;
  } catch (error) {
    console.log(error);
  }
};

export const getColumnsSetApi = async (businessId: string) => {
  try {
    const userId = handleUserId();
    const list = (
      await serverLoading('/bk/api/company/UserCustomization/find', {
        where: { userId: [userId, Admin], businessId }
      })
    )?.rows;
    let result: any;
    if (list?.length > 1) {
      result = list.find((ele: any) => ele.userId !== Admin);
    } else {
      result = list?.find(
        (ele: any) => ele.userId !== Admin || (ele.userId === Admin && ele.shareFlag) || handleUserId() === Admin
      );
    }
    columnsMapObj[cacheKeyFun(businessId)] = result || {};
    return result;
  } catch (error) {}
};

export const delColumnsSetApi = async (id: string, businessId: string) => {
  try {
    await serverLoading('/bk/api/company/UserCustomization/delete', {
      data: { id }
    });
    columnsMapObj[cacheKeyFun(businessId)] = {};
    message.success();
  } catch (error) {}
};
